package com.jiazhong.example.example.rocket.demo1.alipay.listener;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiazhong.example.example.rocket.demo1.commons.bean.Alipay;
import com.jiazhong.example.example.rocket.demo1.commons.bean.Order;
import com.jiazhong.example.example.rocket.demo1.commons.bean.Stock;
import com.jiazhong.example.example.rocket.demo1.commons.mapper.OrderMapper;
import com.jiazhong.example.example.rocket.demo1.commons.mapper.StockMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class AlipayOrderListener implements TransactionListener {
    @Resource
    private StockMapper stockMapper;
    @Resource
    private OrderMapper orderMapper;

    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("开始确认库存是否充足");
        byte[] body = message.getBody();
        String json = new String(body, StandardCharsets.UTF_8);
        Alipay alipay = JSONArray.parseObject(json, Alipay.class);
        log.info("消息是：{}", alipay);

        QueryWrapper<Stock> wrapper = new QueryWrapper<>();
        wrapper.eq("book_id", alipay.getBookId());
        wrapper.select("number");
        Stock stock = stockMapper.selectOne(wrapper);
        log.info("查询出来的结果是：{}", stock);
        Integer stockNumber = stock.getNumber();
        if (stockNumber >= alipay.getNumber()) {
            // 修改订单的状态
            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", alipay.getOut_trade_no());
            updateWrapper.set("status", "2");
            orderMapper.update(updateWrapper);
            return LocalTransactionState.COMMIT_MESSAGE;
        }
        return LocalTransactionState.ROLLBACK_MESSAGE;
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        return null;
    }
}
